import { observable, action, toJS } from 'mobx';
import * as Api from './../apis/unitSetApi';
import { WeaTableNew, WeaForm, WeaLogView } from 'comsMobx';
import { Modal, message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const { LogStore } = WeaLogView;

class UnitStore {
  @observable logType = '';// 板块id
  @observable logSmallType = '';// 板块下面的小模块id
  @observable showAddClerk = true; // 选择添加文员方式div是否显示
  @observable showSearchAd = false; // 高级搜搜form表单是否显示
  @observable logStore = new LogStore();
  @observable logShow = false; // 日志弹窗显示
  @observable topTab = [] // 页签
  @observable unitSelectedRowKeys = [];// 单位选择
  @observable clerkSelectedRowKeys = [];// 文员选择
  @observable unitId = '';// 用来保存单位id值
  @observable clerkId = '';// 用来保存文员id值
  @observable clerkObj = { // 存储文员信息
    lastname: {},
    loginid: {},
    description: {},
    passwordnew: {},
  }
  @observable unitIdArr = [];// 单位存储批量操作是后的id
  @observable clerkIdArr = []; // 文员id数组
  @observable mainTable = { // 单位信息表
    tableStore: new TableStore(),
  }
  @observable clerkTableStore = new TableStore();// 收发文员信息表
  @observable addDialogVisable = false;// 新建弹窗是否显示
  @observable EditdialogVisable = false;// 编辑弹窗是否显示
  @observable selectedKey = '0';// 显示编辑弹窗的指定页面
  @observable form = new WeaForm();// 管理员form表单
  @observable selectForm = new WeaForm();// 管理员TypeForm
  @observable broForm = new WeaForm();// 管理员浏览Form
  @observable clerkForm = new WeaForm();// 文员form
  @observable editClerkForm = new WeaForm();// 文员编辑form
  @observable unitForm = new WeaForm();// 新建单位form
  @observable editUnitForm = new WeaForm();// 编辑单位form
  @observable searchForm = new WeaForm();// 搜索form
  @observable editClerkDialogVisable = false;// 编辑文员弹框
  @observable initialDatas = [];// 字段列表data
  @observable columns = [];// 字段列表列名
  @observable showAdmin = '0';// 判断单位管理员的账号类型
  @observable showClerkForm = '0';// 显示文员的类型
  @observable origin = undefined;
  @observable companyAdmin = false;// 判断是单位管理员还是系统管理员
  @observable isValue = false;// 是否单位管理员有值
  @observable range = 0;
  @observable rerender = 0;//

  @action.bound
  changeVerificationCode () {
    this.range = Math.random();
  }
  @action
  setUnitIdArr = () => {
    this.unitIdArr = [];
  }

  // 对文员操作
  @action.bound clearkOperate (record, index, operate, flag) {
    this.clerkId = record.user_id;
    switch (flag) {
      // 编辑
      case '0':
        this.clerkObj.lastname.value = record.lastname;
        this.clerkObj.loginid.value = record.loginid;
        this.clerkObj.description.value = record.description;
        this.clerkObj.passwordnew.value = record.password;
        this.getClerkForm('edit');
        break;
      // 删除
      case '1':
        this.deleteClerk();
        break;
    }
  }
  // 删除文员
  @action.bound deleteClerk () {
    let params = {};
    if (this.clerkId !== '') {
      params = { user_ids: this.clerkId };
    } else {
      params = { user_ids: this.clerkIdArr.join(',') };
    }
    Api.deleteClerk(params).then((data) => {
      if (data.api_status) {
        message.success(getLabel(83472, '删除成功!'));
        this.getclerkList();
        this.clerkIdArr = [];
      } else {
        message.error(getLabel(83473, '删除失败!'));
      }
    });
    this.clerkId = '';
  }
  // 添加文员
  @action.bound addClerk () {
    if (this.clerkId && this.clerkId != '') {
      const editClerkForm = this.editClerkForm.getFormParams();
      const params = {
        id: this.clerkId,
        from: 'doc',
        passwordnew: editClerkForm.passwordnew,
        validatecode: editClerkForm.validatecode,
        validateRand: this.range,
      };
      Api.editClerk(params).then((data) => {
        if (data.status === '1') {
          const param = {
            id: this.clerkId,
            description: editClerkForm.description,
          };
          Api.editClerkChangePassword(param).then((res) => {
            if (res.api_status) {
              message.success(getLabel(387621, '修改成功!'));
              this.getclerkList();
              this.editClerkDialogVisable = false;
            } else {
              message.error(getLabel(387623, '修改失败!'));
            }
          });
        } else {
          message.error(data.message);
          this.changeVerificationCode();
        }
      });
    } else {
      const clerkForm = this.clerkForm.getFormParams();
      const params = {
        lastname: clerkForm.lastname,
        loginid: clerkForm.loginid,
        password: clerkForm.password,
        from: 'doc',
      };
      Api.inputSaveUnitAdmin(params).then((data) => {
        if (data.status === '1') {
          const params1 = {
            id: this.unitId,
            userId: data.id,
            description: clerkForm.description,
          };
          Api.addClerk(params1).then((res) => {
            if (res.api_status) {
              this.getclerkList();
              this.editClerkDialogVisable = false;
            } else {
              message.error(res.insertError);
            }
          });
        } else {
          message.error(data.message);
        }
      });
    }
  }
  // 保存按钮
  @action.bound saveDialog (saveTreeData) {
    switch (this.selectedKey) {
      case '0':
        this.onCheck(this.editUnitForm, 'saveObj');
        break;
      case '1':
        if (this.showAdmin == '0') {
          this.onCheck(this.form, 'saveUnitAdmin');
        } else {
          this.saveUnitAdmin();
        }
        break;
      case '3':
        saveTreeData();
        break;
    }
  }
  // 对应字段编辑时
  @action.bound fieldChange (data) {
    this.initialDatas = data;
  }
  // 保存对应字段
  @action.bound saveFields () {
    const datas = JSON.stringify(toJS(this.initialDatas));
    const params = { datas };
    Api.saveFields(params).then(() => {
      // if(data.api_status){
      //   message.success(getLabel(387621,"修改成功!"));
      // }else{
      //   message.error(getLabel(387623,"修改失败!"));
      // }
    });
  }
  // 保存单位管理员
  @action.bound saveUnitAdmin () {
    if (this.showAdmin == '0' && !this.isValue) {
      const form = this.form.getFormParams();
      const params = {
        lastname: form.lastname,
        loginid: form.loginid,
        password: form.password,
        from: 'doc',
      };
      Api.inputSaveUnitAdmin(params).then((data) => {
        if (data.status === '1') {
          const datas = { admin_userid: data.id, id: this.unitId };
          Api.saveAdmin(datas).then((res) => {
            if (res.api_status) {
              message.success(getLabel(30700, '操作成功!'));
              this.getUnitAdmin();
            }
          });
        } else {
          message.error(data.message);
        }
      });
    } else if (this.showAdmin == '1') {
      const broForm = this.broForm.getFormParams();
      const params = {
        resourceids: broForm.resourceids,
        from: 'doc',
      };
      Api.broSaveUnitAdmin(params).then((data) => {
        if (data.status === '1') {
          const datas = { admin_userid: broForm.resourceids, id: this.unitId };
          Api.saveAdmin(datas).then((res) => {
            if (res.api_status) {
              message.success(getLabel(83885, '操作成功!'));
              this.getUnitAdmin();
            } else {
              message.error(res.api_errormsg);
            }
          });
        } else {
          message.error(data.message);
        }
      });
    } else if (this.showAdmin == '0' && this.isValue) {
      const form = this.form.getFormParams();
      const params = {
        lastname: form.lastname,
        id: this.unitId,
      };
      Api.saveAdmin(params).then((res) => {
        if (res.api_status) {
          this.getUnitAdmin();
          message.success(getLabel(83885, '操作成功!'));
        } else {
          message.error(getLabel(387623, '修改失败!'));
        }
      });
    }
  }
  // 获取文员信息表单
  @action.bound getClerkForm (type) {
    Api.getClerkForm().then((data) => {
      if (data.api_status) {
        if (type == 'edit') {
          data.addGroupsEdit[0].items.map((item) => {
            for (let key in this.clerkObj) {
              if (item.domkey[0] == key) {
                item.value = this.clerkObj[key].value;
              }
            }
          });
        }
        if (type == 'edit') {
          const condition = data.addGroupsEdit;
          this.editClerkForm = new WeaForm();
          this.editClerkForm.setCondition(condition);
          this.showClerkForm = '1';
        } else {
          const condition = data.items;
          this.showClerkForm = '0';
          this.clerkForm = new WeaForm();
          this.clerkForm.setCondition(condition);
        }
        this.editClerkDialogVisable = true;
        this.showAddClerk = true;
      } else {
        message.error(getLabel(387626, '出错了!'));
      }
    });
  }
  // 获取单位信息table数据
  @action.bound getTableList (text) {
    this.showSearchAd = false;
    const formData = this.searchForm.getFormParams();
    const params = {
      company_name: formData.company_name || text || '',
      company_oa_addr: formData.company_oa_addr || '',
      company_code: formData.company_code || '',
    };
    Api.getData(params).then((data) => {
      const { sessionkey } = data;
      this.companyAdmin = data.companyAdmin;
      if (data.companyAdmin) {
        this.selectedKey = '2';
      }
      if (sessionkey) {
        this.mainTable.tableStore.getDatas(sessionkey);
      }
    });
  }
  // 勾选时批量键可点击
  @action.bound onRowSelect (arr) {
    this.unitIdArr = arr;
  }
  // 勾选时批量删除可点击
  @action.bound clerkOnRowSelect (arr) {
    this.clerkIdArr = arr;
  }

  // 保存单位
  @action.bound saveObj () {
    const formData = this.unitForm.getFormParams();
    const editUnitForm = this.editUnitForm.getFormParams();
    const params = {
      id: this.unitId,
      company_name: formData.company_name || editUnitForm.company_name,
      company_oa_addr: formData.company_oa_addr || editUnitForm.company_oa_addr,
      company_code: formData.company_code || editUnitForm.company_code,
    };
    Api.addData(params).then((data) => {
      if (data.api_status) {
        this.getTableList();
        this.addDialogVisable = false;
        message.success(getLabel(384136, '操作成功!'));
        this.unitForm.resetForm();
      } else {
        message.error(data.api_errormsg);
      }
    });
  }
  // 保存并进入设置
  @action.bound saveAndSet () {
    const formData = this.unitForm.getFormParams();
    const params = {
      id: this.unitId,
      ...formData,
      company_name: formData.company_name.trim(),
      // company_oa_addr: formData.company_oa_addr,
      // company_code: formData.company_code
    };
    Api.addAndSet(params).then((data) => {
      if (data.api_status) {
        this.getTableList();
        this.addDialogVisable = false;
        this.unitId = data.id;
        this.EditdialogVisable = true;
        this.selectedKey = '0';
        this.unitForm.resetForm();
        this.editUnit();
      } else {
        message.error(data.api_errormsg);
      }
    });
  }

  // 点击新建按钮显示弹窗
  @action.bound showDialog () {
    this.addDialogVisable = true;
    this.unitForm.resetForm();
    this.unitId = '';
  }
  // 关闭新建弹窗
  @action.bound hideAddDialog () {
    this.addDialogVisable = false;
    this.unitForm.resetForm();
  }
  // 关闭编辑弹窗
  @action.bound hideEditDialog () {
    this.editUnitForm.resetForm();
    this.clerkForm.resetForm();
    this.EditdialogVisable = false;
    this.mainTable.tableStore.setSelectedRowKeys([]);// 清空选择
    this.rerender = Math.random();
    this.unitIdArr = [];
    this.showAddClerk = true;
    if (this.companyAdmin) {
      this.selectedKey = '2'
    } else {
      this.selectedKey = '0';
    }
  }
  // 删除数据
  @action.bound deleteData () {
    const ids = this.unitIdArr.join(',');
    const params = { ids };
    Api.deleteData(params).then((data) => {
      if (data.api_status) {
        this.getTableList();
        message.success(getLabel(83472, '删除成功!'));
        this.mainTable.tableStore.setSelectedRowKeys([]);// 清空选择
        this.unitIdArr = [];
      } else {
        message.error(data.api_errormsg);
      }
    });
  }
  // 删除数据时提示
  @action.bound deleteTip () {
    Modal.confirm({
      title: getLabel(131329, '信息确认'),
      content: getLabel(83600, ' 您确认要删除吗？'),
      okText: getLabel(33703, ' 确认'),
      cancelText: getLabel(31129, ' 取消'),
      onOk: () => {
        this.deleteData();
      },
      onCancel: () => {
        this.unitIdArr = [];
        this.mainTable.tableStore.setSelectedRowKeys([]);// 清空选择
        this.selectedKey = '0'
      },
    });
  }
  // 操作
  @action.bound operate (record, index, operate, flag) {
    this.unitId = record.id || this.unitId;
    this.unitIdArr = [];
    this.unitIdArr.push(record.id);
    this.selectedKey = flag;
    this.getUnitField();
    switch (flag) {
      // 编辑
      case '0':
        this.editUnit();
        this.EditdialogVisable = true;
        break;
      // 单位管理员
      case '1':
        this.getUnitAdmin();
        this.EditdialogVisable = true;
        break;
      // 收发文员管理
      case '2':
        this.getclerkList();
        this.EditdialogVisable = true;
        break;
      // 对应字段
      case '3':
        this.EditdialogVisable = true;
        break;
      case '4':
        this.getRecUnitTable();
        this.EditdialogVisable = true;
        break;
      // 删除
      case '5':
        this.deleteTip();
        break;
      // 日志
      case '6':
        this.showLog();
        break;
    }
  }
  // 日志显示
  @action.bound showLog () {
    this.logShow = true;
  }
  // 获取新建单位和基本信息表单
  @action.bound getBaseInfo () {
    Api.getBaseInfo().then((data) => {
      if (data.api_status) {
        this.unitForm.setCondition(data.conditions);
      }
    });
  }
  // 获取单位管理员
  @action.bound getUnitAdmin () {
    const id = this.unitId || '';
    const params = { id };
    Api.getUnitAdmin(params).then((data) => {
      if (data.api_status) {
        this.selectForm = new WeaForm();
        this.form = new WeaForm();
        this.broForm = new WeaForm();
        this.selectForm.setCondition(data.addGroupsType);
        this.form.setCondition(data.addGroupsForm);
        this.broForm.setCondition(data.addGroupsBro);
        if (data.optionsType) {
          this.showAdmin = data.optionsType;
          this.isValue = true;
          this.origin = data.optionsType;
        } else {
          this.showAdmin = '0';
          this.isValue = false;
        }
      }
    });
  }
  // 获取文员列表
  @action.bound getclerkList () {
    const params = { id: this.unitId };
    Api.getClerkList(params).then((data) => {
      const { sessionkey } = data;
      if (sessionkey) {
        this.clerkTableStore.getDatas(sessionkey, 1, 10);
      }
    });
  }
  // 获取弹出框的页签
  @action.bound getTabData () {
    Api.getTabData().then((data) => {
      this.topTab = data.topTab;
    });
  }
  // 获取对应字段
  @action.bound getUnitField () {
    const params = { id: this.unitId };
    Api.getUnitField(params).then((data) => {
      this.initialDatas = data.dataInfoItem.datas;
      this.columns = data.dataInfoItem.columns;
      if (data.dataInfoItem.isNeedSave) {
        this.saveFields();
      }
    });
  }
  // 高级搜索显隐
  @action.bound setShowSearchAd () {
    this.showSearchAd = !this.showSearchAd;
  }
  // form表单校验
  @action.bound onCheck (form, type) {
    this.unitIdArr = [];
    this.clerkIdArr = [];
    form.validateForm().then((f) => {
      if (f.isValid) {
        switch (type) {
          case 'saveObj': {
            this.saveObj();
            break;
          }
          case 'saveAndSet': {
            this.saveAndSet();
            break;
          }
          case 'saveUnitAdmin': {
            this.saveUnitAdmin();
            break;
          }
          case 'addClerk': {
            this.addClerk();
            break;
          }
          case 'saveRecUnit': {
            this.addOrEditReceiveOrSendUnit();
            break;
          }
        }
      } else {
        f.showErrors();
      }
    });
  }
  // 获取编辑form
  @action.bound editUnit () {
    const params = { id: this.unitId };
    Api.editUnit(params).then((data) => {
      this.editUnitForm = new WeaForm();
      this.editUnitForm.setCondition(data.conditions);
    });
  }
  // 获取搜索form
  @action.bound getSearchForm () {
    Api.getSearchForm().then((data) => {
      this.searchForm.setCondition(data.condition);
    });
  }
  // 浏览按钮添加文员
  @action.bound broAddClerk (ids) {
    this.showAddClerk = true;
    const params = { resourceids: ids, from: 'doc' };
    Api.broSaveUnitAdmin(params).then((data) => {
      if (data.status == '1') {
        const param = { id: this.unitId, userId: ids };
        Api.addClerk(param).then((res) => {
          if (res.api_status) {
            this.clerkIdArr = [];
            this.getclerkList();
            this.editClerkDialogVisable = false;
            this.showAddClerk = true;
            message.success(res.insertError + res.insertSuccess);
          } else {
            message.error(res.insertError);
          }
        });
      } else {
        message.error(getLabel(26772, '添加失败'));
      }
    });
  }
  // 获取单位日志参数
  @action.bound getCompanyLogType () {
    Api.getCompanyLogType().then((data) => {
      this.logType = data.logType;
      this.logSmallType = data.logSmallType;
    });
  }

  /* ----------------收发文单位------------------*/

  @observable recUnitTableStore = new TableStore(); // 收发文单位Tablestore
  @observable recUnitSelectedKeys = [];
  @observable recUnitDialogVisible = false;
  @observable recUnitForm = new WeaForm()
  @observable showRecUnitForm = '0';
  @observable editUnitLogType = '';
  @observable editUnitLogSmallType = '';
  @observable editUnitLogStore = new LogStore();
  @observable editUnitLogVisible = false; // 日志弹窗显示
  // 获取table数据
  @action.bound
  getRecUnitTable () {
    const pramas = { systemCode: this.unitId };
    Api.getRecUnitTable(pramas).then((data) => {
      if (data.sessionkey) {
        this.editUnitLogSmallType = data.logSmallType;
        this.editUnitLogType = data.logType;
        this.recUnitTableStore.getDatas(data.sessionkey, 1, 10);
      }
    });
  }

  // 选中行
  @action.bound
  recUnitRowSelected (selectedKey) {
    this.recUnitSelectedKeys = selectedKey;
  }

  @action.bound
  recUnitDialogShow () {
    this.recUnitDialogVisible = !this.recUnitDialogVisible;
    if (this.recUnitDialogVisible) {
      this.getReceiveOrSendUnitForm();
    } else {
      this.recUnitSelectedKeys = [];
    }
  }

  @action.bound
  getReceiveOrSendUnitForm () {
    const pramas = {
      receiveOrSendUnitId: this.recUnitSelectedKeys.join(','),
    };
    Api.getReceiveOrSendUnitForm(pramas).then((data) => {
      if (data.api_status) {
        this.recUnitForm = new WeaForm();
        this.recUnitForm.setCondition(data.conditions);
      }
    });
  }

  @action.bound
  addOrEditReceiveOrSendUnit () {
    const formData = this.recUnitForm.getFormParams();
    const pramas = {
      ...formData,
      receiveOrSendUnitId: this.recUnitSelectedKeys.join(','),
      systemCode: this.unitId,
    };
    Api.addOrEditReceiveOrSendUnit(pramas).then((data) => {
      if (data.api_status) {
        this.getRecUnitTable();
        this.recUnitDialogShow();
        message.success(getLabel('30700', '操作成功'));
      } else {
        message.error(data.api_errormsg);
      }
    });
  }

  @action.bound
  deleteRecUnit () {
    const pramas = {
      receiveOrSendUnitIds: this.recUnitSelectedKeys.join(','),
    };
    Api.deleteReceiveOrSendUnit(pramas).then((data) => {
      if (data.api_status) {
        this.getRecUnitTable();
        this.recUnitSelectedKeys = [];
        message.success(getLabel('30700', '操作成功'));
      } else {
        message.error(data.api_errormsg);
      }
    });
  }

  @action.bound
  recUnitOperate (record, index, operate, flag) {
    this.recUnitSelectedKeys = [];
    this.recUnitSelectedKeys.push(record.id);
    flag == '0' && this.recUnitDialogShow();
    flag == '1' && this.deleteRecUnit();
  }

  @action.bound editUnitLogShow () {
    this.editUnitLogVisible = true;
  }
}


export default new UnitStore();
